var express = require('express');
var router = express.Router();
var pool = require('../db')
var jwt = require('jsonwebtoken')

var key = 'wang'

// console.log(jwt)


// 登录接口
router.post('/login', function (req, res, next) {
  // post传参  req.body
  // get传参   req.query
  const { userName, passWord } = req.body

  // 查询数据  pool.query(sql, callback)
  // 带条件查询
  // * 如果是字符串类型需要带 ''
  pool.query(`select * from user where name='${userName}' and password='${passWord}'`, (err, data) => {
    if (err) {
      res.send({
        code: 0,
        message: "sql语句错误"
      })
    } else {
      // 如果登录成功 返回token  FJLSAKLDNASDOSADI
      // 1. 生成token  (jsonwebtoken)
      if (data.length > 0) {
        const { userId } = data[0]
        // jwt.sign(要生成token的属性, 生成token的规则, token的配置)
        let token = jwt.sign({ userName, userId }, key, {
          expiresIn: "1h"
        })

        // verify 解析token

        console.log(jwt.verify(token, key))

        res.send({
          code: 1,
          message: "登录成功",
          token
        })
      } else {
        res.send({
          code: 0,
          message: "请去注册"
        })
      }
    }
  })
})


// 列表
router.get('/getList', function (req, res, next) {
  pool.query('select * from list', (err, data) => {
    if (err) {
      res.send({
        code: 0,
        message: err
      })
    } else {
      res.send({
        code: 1,
        message: "查询成功",
        data
      })
    }
  })
})

// 做拦截
const addAuth = (req, res, next) => {
  const { authorization } = req.headers
  // 来解析token
  const data = jwt.verify(authorization, key)
  const { userId } = data 
  if (userId > 1) {
    res.send({
      code: 0,
      message: "权限不足"
    })
  } else {
    next()
  }
}

// 添加接口权限验证
router.post('/addItem', addAuth)
// 添加接口
// get  post  put  delete
router.post('/addItem', function (req, res, next) {
  const { name, short, count } = req.body
  // console.log(name, short, count)

  let sql = `insert into list (name, short, count) values ('${name}', '${short}', ${count})`
  pool.query(sql, (err, data) => {
    console.log(err, data)
    if (err) {
      res.send({
        code: 0,
        message: "sql错误"
      })
    } else {
      res.send({
        code: 1,
        message: "添加成功"
      })
    }
  })

})


module.exports = router;
